import { createRouter, createWebHistory } from 'vue-router'


const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/Login.vue')
    },
    {
        path: '/home',
        name: 'Home',
        component: () => import('../views/Home.vue'),
        children: [
            {
                path: 'books',
                name: 'BookManage',
                component: () => import('../views/BookManage.vue')
            },
            {
                path: 'readers',
                name: 'ReaderManage',
                component: () => import('../views/ReaderManage.vue')
            },
            {
                path: 'borrows',
                name: 'BorrowManage',
                component: () => import('../views/BorrowManage.vue')
            },
            {
                path: 'stats',
                name: 'Stats',
                component: () => import('../views/Stats.vue')
            }
        ]
    },
    {
        path: '/',
        redirect: '/login'
    }
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes
})

//路由守卫,用于判断用户是否登录
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token')
    if (to.path !== '/login' && !token) {
        next('/login')
    } else if (to.path === '/login' && token) {
        next('/home')
    } else {
        next()
    }
})

export default router
